package com.example.shiwu.fragment;

import static androidx.core.content.ContextCompat.getSystemService;

import static com.example.shiwu.util.GeneralUtil.showToast;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.example.shiwu.R;
import com.example.shiwu.db.model.Device;
import com.example.shiwu.db.model.Items;
import com.example.shiwu.db.model.User;
import com.example.shiwu.db.vo.MyQueue;
import com.example.shiwu.model.MainInfo;
import com.example.shiwu.service.DeviceService;
import com.example.shiwu.service.ItemsService;
import com.example.shiwu.service.UserService;
import com.example.shiwu.util.ByteUtil;
import com.example.shiwu.util.Callback;
import com.example.shiwu.util.ContextVariable;
import com.example.shiwu.util.DataParseUtil;
import com.example.shiwu.util.DateUtils;
import com.example.shiwu.util.NetworkUtils;
import com.example.shiwu.util.SharedPreferencesUtii;
import com.example.shiwu.util.SocketMergeCallBackUtils;
import com.example.shiwu.view.MainInfoView;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;

public class MainInfoFragment extends Fragment {
    private String content;
    private MainInfoView mainInfoView;
    private final int STATE_DISCONNECTED = 1;
    private final int STATE_CONNECTING = 2;
    private final int STATE_CONNECTED = 3;
    private int mSocketConnectState = STATE_DISCONNECTED;
    private static final int MSG_TIME_SEND = 1;
    private static final int MSG_SOCKET_CONNECT = 2;
    private static final int MSG_SOCKET_DISCONNECT = 3;
    private static final int MSG_SOCKET_CONNECTFAIL = 4;
    private static final int MSG_RECEIVE_DATA = 5;
    private static final int MSG_BING_ERROR_DATA = 6;
    private static final int SOCKET_FAIL = 7;
    private static final int SOCKET_SUCCESS_DIALOG = 8;

    private static final int DIALOG_CANCEL = 9;
    public Socket mSocket;

    private SharedPreferences mSharedPreferences;
    private SharedPreferences.Editor editor;
    private final int DEFAULT_PORT = 8086;
    private int mClientPort = 8080; //端口,默认为8086，可以进行设置
    private OutputStream mOutStream;
    private InputStream mInStream;
    private Handler mSubThreadHandler;
    private HandlerThread mHandlerThread;
    private TextView edition;
    private View view;
    private int success_count = 0;
    private Boolean bool = true;
    private ArrayList<String> msgArray;
    private MyQueue queue, queueMaininfo;;
    private DataParseUtil dataParseUtil;
    private DeviceService deviceService;
    private ItemsService itemsService;
    private String itemsId="";
    private String deviceId = "";
    private String userName = "";
    private String sn="";
    private String boxAddr = "";
    //private SocketInfoUtils socketUtils;
    private SocketMergeCallBackUtils socketUtils;
    private ZLoadingDialog dialog;
    private ConnectivityManager.NetworkCallback networkCallback;

    private View mRootView; // 缓存视图
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIME_SEND:
                    break;
                case MSG_RECEIVE_DATA:
                    MainInfo mainInfo = new MainInfo();
                    ArrayList msglis = (ArrayList) msg.obj;
                    UserService userService = new UserService();
                    User user = userService.getLoginUser();
                    String uName = user.getName();
                    if(msglis.size()>0){

                        Device device = new Device();
                        List<Device> lis_dev = deviceService.getDevice(device);
                        device.setBox(msglis.get(0).toString());
                        device.setSn(msglis.get(1).toString());
                        if(uName.equals("swAdmin")){
                            mainInfo.setGps(msglis.get(0).toString());
                            mainInfo.setSn(msglis.get(1).toString());
                            mainInfo.setPowerSource(msglis.get(2).toString());
                            mainInfo.setChannel(msglis.get(3).toString());
                            mainInfo.setVoltage(msglis.get(4).toString());
                            mainInfo.setTemp(msglis.get(5).toString());
                            mainInfo.setIntemp(msglis.get(6).toString());
                            mainInfo.setOutEle(msglis.get(7).toString());

                            device.setStatus(1);
                            mainInfo.setFirmwareeDition(msglis.get(1).toString());
                            initView(mainInfo);
                        }else {
                            if(lis_dev.get(0).getStatus() != 1){
                                device.setStatus(0);
                                dialog.cancel();
                                Toast.makeText(view.getContext(), "设备绑定失败！", Toast.LENGTH_SHORT).show();
                            }else {
                                mainInfo.setGps(msglis.get(0).toString());
                                mainInfo.setSn(msglis.get(1).toString());
                                mainInfo.setPowerSource(msglis.get(2).toString());
                                mainInfo.setChannel(msglis.get(3).toString());
                                mainInfo.setVoltage(msglis.get(4).toString());
                                mainInfo.setTemp(msglis.get(5).toString());
                                mainInfo.setIntemp(msglis.get(6).toString());
                                mainInfo.setOutEle(msglis.get(7).toString());

                                mainInfo.setFirmwareeDition(msglis.get(1).toString());
                                initView(mainInfo);
                            }

//                            return;
                        }

                        if(!itemsId.equals("")){
                            device.setItemId(itemsId);
                        }
                        if(lis_dev.size()==0){
                            device.setCreateTime(DateUtils.parseDate());
                            deviceService.save(device);
                        }else {
                            device.setUpdateTime(DateUtils.parseDate());
                            deviceService.updata(device,new Device());
                        }

                    }
                    dialog.cancel();
                    msgArray.clear();
//                    if (socketUtils != null) {
//
//                        socketUtils.isReConnect = true;
//                        socketUtils.releaseSocket();
//                    }
                    break;
                case SOCKET_FAIL:
                    Toast.makeText(view.getContext(), "网络未连接！", Toast.LENGTH_SHORT).show();
                    break;
                case SOCKET_SUCCESS_DIALOG:
                    dialog = new ZLoadingDialog(getActivity());
                    dialog.setLoadingBuilder(Z_TYPE.DOUBLE_CIRCLE)//设置类型
                            .setLoadingColor(Color.BLUE)//颜色
                            .setHintText("读取中.")
                            .setCanceledOnTouchOutside(false)
                            .show();
                    break;
                case MSG_BING_ERROR_DATA:
                    dialog.cancel();
                    Toast.makeText(view.getContext(), "设备绑定失败！", Toast.LENGTH_SHORT).show();
                    break;
                case DIALOG_CANCEL:
                    dialog.cancel();
                    break;
                default:
                    break;
            }
        };
    };

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_maininfo, container, false);
        Log.d("maininfo","onCreateViewOut == "+savedInstanceState);
//        if (savedInstanceState == null){
//            return view;
//        }
        networkCallback = new ConnectivityManager.NetworkCallback() {
            @Override
            public void onAvailable(Network network) {
                super.onAvailable(network);
                Message msg = new Message();
                msg.what = SOCKET_SUCCESS_DIALOG;
                mHandler.sendMessage(msg);
                Log.d("maininfo","onCreateView");
                showToast(view.getContext(),"网络已连接");
//                NetworkUtils.getConnectivityManager(view.getContext()).unregisterNetworkCallback(networkCallback);
                //initView(null);
                //edition = view.findViewById(R.id.maininfo_firmwaree_dition_val);
                msgArray = new ArrayList<String>();
                //dataParseUtil = new DataParseUtil();
                deviceService = new DeviceService();
                List<Device> deviceList = deviceService.getDevice(new Device());
                UserService userService = new UserService();
                User user = userService.getLoginUser();
                userName = user.getName();
                if(deviceList.size()>0){
                    sn = deviceList.get(0).getSn();
                }

                Items items = findSelectItem();
                queueMaininfo = new MyQueue();
                if(!BeanUtil.isEmpty(items)){
                    itemsId = items.getId().toString();
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {

                        if(socketUtils.socket == null){
                            socketUtils = SocketMergeCallBackUtils.getInstance(view.getContext());
                        }
                        try {
                            Thread.sleep(1000);
                            if(socketUtils.socket != null){
                                socketListener();
                            }

                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }

                    }
                }).start();

                queue = new MyQueue();
            }

            @Override
            public void onLost(Network network) {
                super.onLost(network);
                //socketUtils.releaseSocket();
                showToast(view.getContext(),"网络已断开");
            }

            @Override
            public void onUnavailable() {
                super.onUnavailable();
                showToast(view.getContext(),"网络连接超时或者网络连接不可达");
            }

            @Override
            public void onLinkPropertiesChanged(@NonNull Network network, @NonNull LinkProperties linkProperties) {
                super.onLinkPropertiesChanged(network, linkProperties);
                //showToast(view.getContext(),"网络连接状态改变");
            }
        };

        NetworkUtils.getConnectivityManager(view.getContext()).registerDefaultNetworkCallback(networkCallback);

        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();

    }
    @Override
    public void onPause() {
        super.onPause();
        Message msg1 = new Message();
        msg1.what = DIALOG_CANCEL;
        mHandler.sendMessage(msg1);

        if(networkCallback != null){
            // 释放网络连接
            NetworkUtils.getConnectivityManager(view.getContext()).unregisterNetworkCallback(networkCallback);
            networkCallback = null; // 取消注册后立即置空，防止重复使用
            if(socketUtils != null){
                socketUtils.releaseSocket();//释放socket
            }

        }

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
    @Override
    public void onStop() {
        super.onStop();
    }
    private Items findSelectItem() {
        itemsService = new ItemsService();
        Items items = new Items();
        Items items1 = new Items();
        items.setStatus(1);
        List<Items> lis = null;

        try {
            lis = itemsService.getItems(items);
            if(lis.size()>0){
                items1 = lis.get(0);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return items1;
    }

    public void initView(MainInfo mainInfo) {
        mainInfoView = new MainInfoView((Activity) this.getContext(), R.layout.activity_maininfo, view);
        mainInfoView.createView();
        if (mainInfo != null) {
            mainInfoView.bindView(mainInfo);
        }
    }

    private void socketListener() {
        try {
            if(SocketMergeCallBackUtils.isSocketConnected()){
                SocketMergeCallBackUtils.clrearBufferNew();
                String data1 = "22,M;";
                SocketMergeCallBackUtils.success_count = 0;
                SocketMergeCallBackUtils.writeMsgByte(data1.getBytes(), new Callback() {
                    @Override
                    public void onSuccess(byte[] data) {
                        Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                        String msg = new String(data);
                        if (!msg.equals("")) {
                            //Boolean boo = getStatus(msg);
                            if(msg.equals("0,Success;")){
                                String data2 = "11,s;";
                                SocketMergeCallBackUtils.writeMsgByte(data2.getBytes(), new Callback() {
                                    @Override
                                    public void onSuccess(byte[] data) {
                                        Log.i("SocketClient", "kPcResetAdcLogic 11 Text sent successfully ============= " + new String(data));
                                        String msg = new String(data);
                                        if (!msg.equals("")) {
                                            if (msg.contains(";")) {
                                                String[] lis1 = msg.split(";");
                                                if (lis1.length > 0)  {
                                                    try {
                                                        Thread.sleep(15000);
                                                    } catch (InterruptedException e) {
                                                        throw new RuntimeException(e);
                                                    }
                                                    Boolean bool = true;
                                                    while (bool) {
                                                        byte[] by = SocketMergeCallBackUtils.readMuxBox();

                                                        String bystr = new String(by);
                                                        System.out.println("======================== Success11_00000 bad_param ================" + bystr);

                                                        if (!bystr.equals("")) {
                                                            boxAddr = bystr.trim().replace("12,","").replace(";","");
                                                            getFirmwareVer18();
                                                            bool = false;
                                                            //break;
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure(String errorMessage) {
                                        Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
                                    }
                                });
                            }else {
                                if(msg.equals("0,wait;")){
                                    return;
                                }
                                SocketMergeCallBackUtils.writeMsgByte(data1.getBytes(), new Callback() {
                                    @Override
                                    public void onSuccess(byte[] data) {
                                        Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                                        String msg = new String(data);
                                        if (!msg.equals("")) {
                                            Boolean boo = getStatus(msg);
                                            if(boo){
                                                String data2 = "11,s;";
                                                SocketMergeCallBackUtils.writeMsgByte(data2.getBytes(), new Callback() {
                                                    @Override
                                                    public void onSuccess(byte[] data) {
                                                        Log.i("SocketClient", "kPcResetAdcLogic 11 Text sent successfully ============= " + new String(data));
                                                        String msg = new String(data);
                                                        if (!msg.equals("")) {
                                                            if (msg.contains(";")) {
                                                                String[] lis1 = msg.split(";");
                                                                if (lis1.length > 0)  {
                                                                    try {
                                                                        Thread.sleep(15000);
                                                                    } catch (InterruptedException e) {
                                                                        throw new RuntimeException(e);
                                                                    }
                                                                    Boolean bool = true;
                                                                    while (bool) {
                                                                        byte[] by = SocketMergeCallBackUtils.readMuxBox();

                                                                        String bystr = new String(by);
                                                                        System.out.println("======================== Success11_00000 bad_param ================" + bystr);

                                                                        if (!bystr.equals("")) {
                                                                            boxAddr = bystr.trim().replace("12,","").replace(";","");
                                                                            getFirmwareVer18();
                                                                            bool = false;
                                                                            break;
                                                                        }else {
                                                                            System.out.println("======================== Success11_00000 continue ================");
                                                                            continue;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(String errorMessage) {
                                                        Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
                                                    }
                                                });
                                            }else {
                                                SocketMergeCallBackUtils.writeMsgByte(data1.getBytes());
                                                String data2 = "11,s;";
                                                SocketMergeCallBackUtils.writeMsgByteMuxBox(data2.getBytes(), new Callback() {
                                                    @Override
                                                    public void onSuccess(byte[] data) {
                                                        Log.i("SocketClient", "kPcResetAdcLogic 11 Text sent successfully ============= " + new String(data));
                                                        String msg = new String(data);
                                                        if (!msg.equals("")) {
                                                            if (msg.contains(";")) {
                                                                String[] lis1 = msg.split(";");
                                                                if (lis1.length > 0)  {
                                                                    try {
                                                                        Thread.sleep(15000);
                                                                    } catch (InterruptedException e) {
                                                                        throw new RuntimeException(e);
                                                                    }
                                                                    Boolean bool = true;
                                                                    while (bool) {
                                                                        byte[] by = SocketMergeCallBackUtils.readMuxBox();

                                                                        String bystr = new String(by);
                                                                        System.out.println("======================== Success11_00000 bad_param ================" + bystr);

                                                                        if (!bystr.equals("")) {
                                                                            boxAddr = bystr.trim().replace("12,","").replace(";","");
                                                                            getFirmwareVer18();
                                                                            bool = false;
                                                                            break;
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }

                                                    @Override
                                                    public void onFailure(String errorMessage) {
                                                        Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
                                                    }
                                                });
                                            }
                                        }
                                    }

                                    @Override
                                    public void onFailure(String error) {
                                        Log.e("SocketClient", "Failed to send text: " + error);
                                    }
                                });
                            }
                        }else {
                            SocketMergeCallBackUtils.writeMsgByte(data1.getBytes(), new Callback() {

                                @Override
                                public void onSuccess(byte[] data) throws IOException {
                                    Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                                    String msg = new String(data);
                                    if (!msg.equals("")) {
                                        Boolean boo = getStatus(msg);
                                        if(boo){
                                            String data2 = "11,s;";
                                            SocketMergeCallBackUtils.writeMsgByteMuxBox(data2.getBytes(), new Callback() {
                                                @Override
                                                public void onSuccess(byte[] data) {
                                                    Log.i("SocketClient", "kPcResetAdcLogic 11 Text sent successfully ============= " + new String(data));
                                                    String msg = new String(data);
                                                    if (!msg.equals("")) {
                                                        if (msg.contains(";")) {
                                                            String[] lis1 = msg.split(";");
                                                            if (lis1.length > 0)  {
                                                                try {
                                                                    Thread.sleep(15000);
                                                                } catch (InterruptedException e) {
                                                                    throw new RuntimeException(e);
                                                                }
                                                                Boolean bool = true;
                                                                while (bool) {
                                                                    byte[] by = SocketMergeCallBackUtils.readMuxBox();

                                                                    String bystr = new String(by);
                                                                    System.out.println("======================== Success11_00000 bad_param ================" + bystr);

                                                                    if (!bystr.equals("")) {
                                                                        boxAddr = bystr.trim().replace("12,","").replace(";","");
                                                                        getFirmwareVer18();
                                                                        bool = false;
                                                                        break;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }

                                                @Override
                                                public void onFailure(String errorMessage) {
                                                    Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
                                                }
                                            });
                                        }else {
                                            SocketMergeCallBackUtils.writeMsgByte(data1.getBytes(), new Callback() {
                                                @Override
                                                public void onSuccess(byte[] data) {
                                                    Log.i("SocketClient", "Text sent successfully ============= " + new String(data));
                                                    String msg = new String(data);
                                                    if (!msg.equals("")) {
                                                        Boolean boo = getStatus(msg);
                                                        if(boo){
                                                            String data2 = "11,s;";
                                                            SocketMergeCallBackUtils.writeMsgByteMuxBox(data2.getBytes(), new Callback() {
                                                                @Override
                                                                public void onSuccess(byte[] data) {
                                                                    Log.i("SocketClient", "kPcResetAdcLogic 11 Text sent successfully ============= " + new String(data));
                                                                    String msg = new String(data);
                                                                    if (!msg.equals("")) {
                                                                        if (msg.contains(";")) {
                                                                            String[] lis1 = msg.split(";");
                                                                            if (lis1.length > 0)  {
                                                                                try {
                                                                                    Thread.sleep(1500);
                                                                                } catch (InterruptedException e) {
                                                                                    throw new RuntimeException(e);
                                                                                }
                                                                                Boolean bool = true;
                                                                                while (bool) {
                                                                                    byte[] by = SocketMergeCallBackUtils.readMuxBox();

                                                                                    String bystr = new String(by);
                                                                                    System.out.println("======================== Success11_00000 bad_param ================" + bystr);

                                                                                    if (!bystr.equals("")) {
                                                                                        boxAddr = bystr.trim().replace("12,","").replace(";","");
                                                                                        getFirmwareVer18();
                                                                                        bool = false;
                                                                                        break;
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }

                                                                @Override
                                                                public void onFailure(String errorMessage) {
                                                                    Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
                                                                }
                                                            });
                                                        }else {
                                                            SocketMergeCallBackUtils.writeMsgByte(data1.getBytes());
                                                            String data2 = "11,s;";
                                                            SocketMergeCallBackUtils.writeMsgByteMuxBox(data2.getBytes(), new Callback() {
                                                                @Override
                                                                public void onSuccess(byte[] data) {
                                                                    Log.i("SocketClient", "kPcResetAdcLogic 11 Text sent successfully ============= " + new String(data));
                                                                    String msg = new String(data);
                                                                    if (!msg.equals("")) {
                                                                        if (msg.contains(";")) {
                                                                            String[] lis1 = msg.split(";");
                                                                            if (lis1.length > 0)  {
                                                                                try {
                                                                                    Thread.sleep(1500);
                                                                                } catch (InterruptedException e) {
                                                                                    throw new RuntimeException(e);
                                                                                }
                                                                                Boolean bool = true;
                                                                                while (bool) {
                                                                                    byte[] by = SocketMergeCallBackUtils.readMuxBox();

                                                                                    String bystr = new String(by);
                                                                                    System.out.println("======================== Success11_00000 bad_param ================" + bystr);

                                                                                    if (!bystr.equals("")) {
                                                                                        boxAddr = bystr.trim().replace("12,","").replace(";","");
                                                                                        getFirmwareVer18();
                                                                                        bool = false;
                                                                                        break;
                                                                                    }
                                                                                }
                                                                            }
                                                                        }
                                                                    }
                                                                }

                                                                @Override
                                                                public void onFailure(String errorMessage) {
                                                                    Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
                                                                }
                                                            });
                                                        }
                                                    }
                                                }

                                                @Override
                                                public void onFailure(String error) {
                                                    Log.e("SocketClient", "Failed to send text: " + error);
                                                }
                                            });
                                        }
                                    }
                                }

                                @Override
                                public void onFailure(String error) {

                                }
                            });
                        }
                    }

                    @Override
                    public void onFailure(String errorMessage) {
                        Log.e("SocketClient", "Failed to send text: " + errorMessage);
                        SocketMergeCallBackUtils.writeMsgByte(data1.getBytes(), new Callback() {
                            @Override
                            public void onSuccess(byte[] data) {
                                Log.i("SocketClient time out", "Text sent successfully ============= " + new String(data));
                                String msg = new String(data);
                                if (!msg.equals("")) {
                                    getStatus(msg);
                                }
                            }

                            @Override
                            public void onFailure(String errorMessage) {
                                Log.e("SocketClient", "Failed to send text: " + errorMessage);
                            }
                        });
                    }
                });
            }else {
                return;
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        Log.i("SocketClient time out 22222222222", "Text sent successfully ============= " );

    }
    /**
     * 查询告警，并写入数据库
     * 1.发送18，get;读取success后截取数据，
     * 2.调用getAlarm13方法 发送13,update;命令
     */
    private void getFirmwareVer18() {
        String data = "18,get;";
        SocketMergeCallBackUtils.writeMsg18(data, new Callback() {
            @Override
            public void onSuccess(byte[] data) {
                Log.i("SocketClient", "Alarm 18 Text sent successfully ============= " + new String(data));
                String msg = new String(data);
                if (!msg.equals("")) {
                    String msglis_18 = ByteUtil.byteTransformAscil(data);
                    //System.out.println("  msglis_18 ===================="+ msglis_18);
                    deviceId = msglis_18.split(",")[1];//固件版本
                    SharedPreferencesUtii.putSharedPreferences("deviceId",deviceId,view.getContext());
//                    if (userName.equals("user")){
//                        if(!deviceId.equals(sn)){
//                            Message msg1 = new Message();
//                            msg1.what = MSG_BING_ERROR_DATA;
//                            mHandler.sendMessage(msg1);
//                            return;
//                        }
//                    }
                    if (!deviceId.equals("")) {
                        //读取success后截取数据，再发送13命令
                        getAskSystemInform13();
                    }
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "Alarm 18 Failed to send text: " + errorMessage);
            }
        });
    }

    private void getAskSystemInform13() {
        String data = "13,update;";
        SocketMergeCallBackUtils.writeMsg14(data, new Callback() {
            @Override
            public void onSuccess(byte[] data) throws UnsupportedEncodingException {
                Log.i("SocketClient", "Alarm 13 Text sent successfully ============= " + new String(data, "utf-8"));
                String msg = Arrays.toString(data);
                for (byte b : data) {
                    queueMaininfo.enQueue(b);
                }
                try {
                    for (int i = 0; i < 3; i++) {
                        queueMaininfo.deQueue();
                    }
                    Double batt_vol = Double.valueOf(receive_one_field_alarm());//电源
                    System.out.println("  电源电压222 ====================" + batt_vol);

                    String tx_high_vol1 = receive_one_field_alarm();//高压
                    String tx_high_vol = "";
                    if (tx_high_vol1.length() > 1) {
                        tx_high_vol = tx_high_vol1.substring(0, tx_high_vol1.indexOf(".")) + "V";//主机电压
                    } else {
                        tx_high_vol = tx_high_vol1 + "V";
                    }

                    String temperature1 = receive_one_field_alarm();//温度
                    System.out.println("  温度 ====================" + temperature1);
                    String temperature = "";
                    if (temperature1.length() > 1) {
                        temperature = temperature1.substring(0, temperature1.indexOf(".")) + "°C";//温度
                    } else {
                        temperature = temperature1 + "°C";//温度
                    }

                    String humidity1 = receive_one_field_alarm();//湿度
                    String humidity = "";//湿度
                    if (humidity1.length() > 1) {
                        humidity = humidity1.substring(0, humidity1.indexOf(".")) + "°C";//湿度
                    } else {
                        humidity = humidity1 + "°C";
                    }

                    String alarm = receive_one_field_alarm();//告警
                    String outEle = receive_one_field_outEle();//外部电源

                    int batt_vol_int = batt_vol.intValue();
                    BigDecimal a = new BigDecimal(batt_vol_int);
                    BigDecimal b = new BigDecimal(ContextVariable.power_supply);
                    BigDecimal c = a.divide(b, 1, BigDecimal.ROUND_HALF_UP);
                    String batt_percent = String.valueOf(c.multiply(new BigDecimal(100)));
                    int batt_percent_val1 = Integer.parseInt(batt_percent.substring(0, batt_percent.indexOf(".")));
                    if (batt_percent_val1 > 100) {
                        batt_percent_val1 = 100;
                    }
                    String batt_percent_val = batt_percent_val1 + "%";

                    if(batt_vol != 0 && !tx_high_vol.equals("") &&
                            !temperature1.equals("") && !humidity1.equals("") &&
                            !alarm.equals("")&& !outEle.equals("")){
                        msgArray.add(boxAddr);
                        msgArray.add(deviceId);
                        msgArray.add(batt_percent_val);
                        msgArray.add(ContextVariable.channel);
                        msgArray.add(tx_high_vol);
                        msgArray.add(temperature);
                        msgArray.add(humidity);

                        if(outEle.equals("plugin")){
                            msgArray.add("已接入");
                        }else {
                            msgArray.add("未接入");
                        }

                        Message msg1 = new Message();
                        msg1.what = MSG_RECEIVE_DATA;
                        msg1.obj = msgArray;
                        mHandler.sendMessage(msg1);
                    }

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            public void onFailure(String errorMessage) {
                Log.e("SocketClient", "kPcResetAdcLogic 23 Failed to send text: " + errorMessage);
            }
        });
    }

    private boolean getStatus(String message) {
        Boolean stabool = false;
        if (message.contains("0,Success;") && !message.equals("")) {
            System.out.println("======================== Success bad_param ================" + message);
            stabool = true;
        } else if (message.contains("0,wait;")) {
            System.out.println("======================== wait bad_param ================" + message);
            stabool = false;
        } else if (message.contains("0,Timeout;")) {
            System.out.println("======================== bad_param ================" + message);
            System.out.println(" kSetMuxBoxConnect switch box connect error ");
            stabool = false;
            String msg1 = "开关盒子连接出错！";
        } else if (message.equals("0,Bad_Param;") || message.equals("0,BadParam;")) {
            System.out.println("======================== bad_param ================" + message);
            stabool = false;
            String msg1 = "ABMN配置错误！";
        } else if (message.equals("0,alarm;")) {
            System.out.println("========================alarm bad_param ================" + message);
        } else if (message.equals("None")) {
            System.out.println(" usb/wifi connect error ");
            stabool = false;
        } else if (message.contains("kErrorAlarm")) {//告警写入
            System.out.println(" kErrorAlarm================= " + message);
        } else if (message.equals("null")) {
        }
        return stabool;
    }

    public synchronized String receive_one_field_alarm() throws InterruptedException, UnsupportedEncodingException {
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean bl = true;
        String msgbt = "";
        while (bl) {

            byte tmp = (byte) queueMaininfo.deQueue();
            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
                } else {
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                } else {
                    one_field.add(tmp);
                }
            }

        }
        if (one_field.size() > 0) {
            msgbt = SocketMergeCallBackUtils.recv_float_alarm(one_field);
        }

        return msgbt;
    }

    public synchronized String receive_one_field_outEle() throws InterruptedException, UnsupportedEncodingException {
        Boolean escaped = false;
        Boolean command_sep_found = false;
        ArrayList<Byte> one_field = new ArrayList<Byte>();
        Boolean bl = true;
        String msgbt = "";
        while (bl) {

            byte tmp = (byte) queueMaininfo.deQueue();
            if (escaped) {
                if (tmp == 44 || tmp == 59 || tmp == 47) {
                    one_field.add(tmp);
                    escaped = false;
                } else {
                    one_field.add(tmp);
                    escaped = false;
                }
            } else {
                if (tmp == 47) {
                    //遇到 / 就escaped = True 继续循环
                    escaped = true;
                } else if (tmp == 44) {
                    break;
                } else if (tmp == 59) {
                    command_sep_found = true;
                    break;
                } else {
                    one_field.add(tmp);
                }
            }

        }
        if (one_field.size() > 0) {
            msgbt = SocketMergeCallBackUtils.recv_string_ele(one_field);
        }

        return msgbt;
    }

}
